<?php

/**
 * author : rookiejin <mrjnamei@gmail.com>
 * createTime : 2018/1/23 10:07
 * description: MiPush.php - wingedcare-admin
 */
namespace App\Winged\Common\Service ;

use Illuminate\Support\Facades\Redis;
use Rookiejin\Xmpush\Builder;
use Rookiejin\Xmpush\Constants;
use Rookiejin\Xmpush\IOSBuilder;
use Rookiejin\Xmpush\Sender;

class MiPush
{
    const ANDROID_PUSH_APPID = "android_push_appid";
    const ANDROID_PUSH_APPKEY = "android_push_appkey";
    const ANDROID_PUSH_SECRET = "android_push_secret";
    const ANDROID_PUSH_PACKAGE = "android_push_package";

    const IOS_PUSH_APPID = "ios_push_appid";
    const IOS_PUSH_APPKEY = "ios_push_appkey";
    const IOS_PUSH_SECRET = "ios_push_secret";
    const IOS_PUSH_PACKAGE = "ios_push_package";

    public static function push($title ,$description,$data)
    {
        $config = app()->tenant->getDeaprtmentDomain();
        if(!is_array($config))
        {
            return false ;
        }

        $res = [];

        /* android 推送 */
        foreach ($config as $department) {
            $secret = Redis::get($department . '#' . self::ANDROID_PUSH_SECRET);
            $package = Redis::get($department . '#' . self::ANDROID_PUSH_PACKAGE);
            if(!empty($secret) && !empty($package)){
                Constants::setPackage($package);
                Constants::setSecret($secret);
                $message = self::buildMessage($title,$description,$data);
                $res [$department]['android'] = self::doPush($message);
            }
        }

        /* ios 推送 */
        foreach ($config as $department) {
            $secret = Redis::get($department . '#' . self::IOS_PUSH_SECRET);
            $package = Redis::get($department . '#' . self::IOS_PUSH_PACKAGE);
            if(!empty($secret) && !empty($package)){
                Constants::setBundleId($package);
                Constants::setSecret($secret);
//                Constants::useSandbox();
                $message = self::buildMessageIOS($title,$data);
                $res [$department]['ios'] =self::doPush($message);
            }
        }
        return $res ;
    }

    private static function doPush($message)
    {
        $sender = new Sender();
        return $sender->broadcastAll($message)->getRaw();
    }

    private static function buildMessage($title,$description,$data)
    {
        $message = new Builder();
        $message->title($title) ;
        $message->description($description);
        $message->passThrough(0);
        $message->payload($data);
        $message->extra(Builder::notifyForeground,1);
        $message->notifyId(2);
        $message->build();
        return $message;
    }

    private static function buildMessageIOS($title,$data)
    {
        $message = new IOSBuilder();
        $message->description($title);
        $message->soundUrl("default");
//        $message->badge('4');
        $message->extra("payload",$data);
        $message->build();
        return $message;
    }
}
